package plugins.detail;

import kd.bos.ext.form.container.MessageCarouselContainer;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.url.UrlService;
import java.util.*;

public class ShowNewDishes extends AbstractFormPlugin {

    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        loadDishesImagesToCarousel();
    }

    private void loadDishesImagesToCarousel() {
        // 1. 获取轮播容器控件
        MessageCarouselContainer carousel =
                (MessageCarouselContainer) this.getView().getControl("dcb4_messagecarouselcont2");

        // 2. 查询所有菜品记录（按倒序排列）
        String entityName = "dcb4_dishes";
        String selectFields = "dcb4_picture";
        QFilter[] filters = new QFilter[0];
        String orderBy = "number desc";
        int top = 64; // 取64条数据

        DynamicObject[] dishesCollection =
                BusinessDataServiceHelper.load(entityName, selectFields, filters, orderBy, top);

        if (dishesCollection == null || dishesCollection.length == 0) {
            return;
        }

        // 3. 构造轮播数据
        List<Map<String, Object>> carouselData = new ArrayList<>();
        Map<String, Object> currentPage = new HashMap<>(); // 当前轮播页
        int itemCount = 0; // 当前页已添加的项数

        for (int i = 0; i < dishesCollection.length; i++) {
            // 每8个菜品开始新的一页
            if (i % 8 == 0 && i > 0) {
                carouselData.add(currentPage);
                currentPage = new HashMap<>();
                itemCount = 0;
            }

            // 获取图片路径
            String localImagePath = dishesCollection[i].getString("dcb4_picture");
            String imageFullUrl = (localImagePath != null && !localImagePath.isEmpty())
                    ? UrlService.getImageFullUrl(localImagePath)
                    : "";

            // 确定控件标识 (dcb4_imageap01 到 dcb4_imageap08)
            String controlKey = "dcb4_imageap0" + (itemCount + 1);

            // 构造图片控件属性
            Map<String, Object> imageProps = new HashMap<>();
            imageProps.put("imageKey", imageFullUrl);

            // 添加到当前页
            currentPage.put(controlKey, imageProps);
            itemCount++;
        }

        // 添加最后一页（可能不满8项）
        if (!currentPage.isEmpty()) {
            carouselData.add(currentPage);
        }

        // 4. 注入数据到轮播容器
        carousel.setData(carouselData);

        /*
        // 调试信息
        this.getView().showSuccessNotification(
                "加载完成: " + dishesCollection.length + "条记录，" +
                        carouselData.size() + "个轮播页"
        );

         */
    }
}
